﻿using AspDotNet.Core6.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Text;

namespace AspDotNet.Core6.WebApi.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    [Produces("application/json")]
    [Consumes("application/json")]
    public class ReceiveJsonController : ControllerBase
    {
        [HttpPost]
        public IActionResult GetObject(object person)
        {
            return Ok(person);
        }

        [HttpPost]
        public IActionResult GetPerson(Person person)
        {
            return Ok(person);
        }

        [HttpPost]
        public string JsonStringBody([FromBody] string content)/* 此内容必须是字符串,不带双引号会出现405的错误,即:"123456abc" */
        {
            return content;
        }

        [HttpPost]
        public string GetStringBody([FromBody] string content)
        {
            return content;
        }

        [HttpPost]
        [Consumes("application/json")]
        public IActionResult GetObjectByFromBody([FromBody] object person)
        {
            return Ok(new { json = person });
        }

        [HttpPost]
        public async Task<IActionResult> GetJson()
        {
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                string rawValue = await reader.ReadToEndAsync();
                return Ok(JsonConvert.DeserializeObject(rawValue));
            }
        }

        [HttpPost]
        [Consumes("application/json")]
        public async Task<IActionResult> GetJsonWithContentType()
        {
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                string rawValue = await reader.ReadToEndAsync();
                return Ok(JsonConvert.DeserializeObject(rawValue));
            }
        }


        [HttpPost]
        public async Task<byte[]> RawBinaryDataManual()
        {
            using (var ms = new MemoryStream(2048))
            {
                await Request.Body.CopyToAsync(ms);
                return ms.ToArray();/* 自动转换为Base64字符串 */
            }
        }
    }

}
